package ru.hh.school;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;

public class UserInput implements Runnable {
    private InputStream stream;
    private ChatRouter router;
    private User user;

    public UserInput(InputStream stream, User user, ChatRouter router) throws IOException {
        this.stream = stream;
        this.user = user;
        this.router = router;
    }

    public void run() {
        try {
            ObjectInputStream stream = new ObjectInputStream(this.stream);
            while (!Thread.interrupted()) {
                String message = (String) stream.readObject();
                router.command(user, message);
            }
        } catch (IOException e) {
            router.command(user, "/quit Disconnected");
        } catch (ClassNotFoundException e) {
            router.command(user, "/quit Wrong protocol");
        } finally {
            try {
                if (stream != null) {
                    stream.close();
                }
            } catch (IOException e) {
                //ignore
            }
        }

    }
}
